package com.hp.gateway_service.filter;

import com.hp.common_api.entity.UserInfo;
import com.hp.common_api.util.JwtUtil;
import com.hp.common_api.util.RsaUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 对所有请求进行拦截，放行登录成功的请求
 */
@Slf4j
//@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {

    public static final String[] WHITE_LIST = {"/login","/logout"};

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        log.info("当前请求："+request.getURI().getPath());
        //放行不拦截的请求
        for(String str : WHITE_LIST){
            if(request.getURI().getPath().endsWith(str)){
                return chain.filter(exchange);
            }
        }
        try {
            //读取cookie中的token
            String token = request.getCookies().getFirst("token").getValue();
            //解析该token为用户对象
            UserInfo user = JwtUtil.getUserInfoFromToken(token, RsaUtil.publicKey);
            log.info("登录成功！" + user);
        } catch (Exception e) {
            e.printStackTrace();
            //拦截请求
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            String msg = "Request Denied!!";
            DataBuffer wrap = response.bufferFactory().wrap(msg.getBytes());
            return response.writeWith(Mono.just(wrap));
        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
